package com.ybu.oodd.utils.aes;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AESUtil {

    // 必须与前端一致
    private static final String SECRET_KEY = "offerduoduo20259"; // 16/24/32 字符
    private static final String IV = "2025092320250923"; // 16 字符

    /**
     * AES 解密（CBC 模式，PKCS5Padding）
     * @param encrypted Base64 编码的密文
     * @return 明文字符串
     */
    public static String decrypt(String encrypted) {
        try {
            // Base64 解码
            byte[] encryptedBytes = Base64.getDecoder().decode(encrypted);

            // 密钥和 IV
            SecretKeySpec keySpec = new SecretKeySpec(
                SECRET_KEY.getBytes(StandardCharsets.UTF_8),
                "AES"
            );
            IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));

            // 解密
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("AES 解密失败", e);
        }
    }
}